//
//  AWSGuidelines.m
//  SLAppProduct
//
//  Created by Alan Wang on 2018/4/20.
//  Copyright © 2018年 Sunline. All rights reserved.
//

#import "AWSGuidelines.h"
//#define KISIphoneX (CGSizeEqualToSize(CGSizeMake(375.f, 812.f), [UIScreen mainScreen].bounds.size) || CGSizeEqualToSize(CGSizeMake(812.f, 375.f), [UIScreen mainScreen].bounds.size))
//#define kSafeAreaTopHeight (KISIphoneX? 88 : 64)

#define IPHONE_X ({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);})


/**
 *导航栏高度
 */
#define kSafeAreaTopHeight (IPHONE_X ? 88 : 64)
@implementation AWSGuidelinesItem

@end

@interface AWSGuidelines()
@property(nonatomic,strong) UIWindow * curWindow;
@property(nonatomic,strong) UIView * contentView;
@property(nonatomic,assign) NSUInteger stepIndex;
@property(nonatomic,copy)  NSArray <AWSGuidelinesItem*>* dataSource;

//容器视图
@property (nonatomic, weak)   CAShapeLayer   *fillLayer;
//绘制路径 用于不需要显示的图片高亮
@property (nonatomic, strong) UIBezierPath   *overlayPath;


@end
@implementation AWSGuidelines
static AWSGuidelines* _instance = nil;

+(instancetype) shareInstance
{
static dispatch_once_t onceToken ;
dispatch_once(&onceToken, ^{
    _instance = [[self alloc] init] ;
    _instance.type = AWSGuidelinesType_OneByOne;
    _instance.stepIndex = 0;
}) ;

return _instance ;
}

+(void)showGuidelinesWithData:(NSArray<AWSGuidelinesItem*>*)itemArr{
    AWSGuidelines * guidelines = [AWSGuidelines shareInstance];
    [guidelines configGuidelinesWithData:itemArr];
    [guidelines showGuidelines];
}

-(void)configGuidelinesWithData:(NSArray<AWSGuidelinesItem*>*)itemArr{
    self.dataSource = itemArr;
}
-(void)showGuidelines{
    if (!self.dataSource) {
        return;
    }
    [self clearContentView];
    self.fillLayer = nil;
    [self fillLayer];
    switch (self.type) {
        case AWSGuidelinesType_OneByOne:{
          [self confightOneItem:self.dataSource[0]];
        }break;
        case AWSGuidelinesType_Once:{
            for (AWSGuidelinesItem * item in self.dataSource) {
                [self confightOneItem:item];
            }
        }break;
        default:
            break;
    }
    if(self.contentView.subviews.count){
      [self.curWindow addSubview:self.contentView];
    }
}

-(void)confightOneItem:(AWSGuidelinesItem*)item{
    if(item.soureceView){//如果有指定的视图就需要修正位置
        CGRect rect = item.tipsView.frame;//获取提示视图的宽高

        CGRect soureceViewInWindows = [item.soureceView.superview convertRect:item.soureceView.frame toView:self.curWindow];
        
        switch (item.type) {
            case AWSGuidelinesItemPotionType_Top:
            {
                item.tipsView.frame = [self topFrame:soureceViewInWindows target:rect item:item];
            }break;
            case AWSGuidelinesItemPotionType_Left:
            {
                item.tipsView.frame = [self leftFrame:soureceViewInWindows target:rect  item:item];
                
            }break;
            case AWSGuidelinesItemPotionType_Right:
            {
                item.tipsView.frame = [self rightFrame:soureceViewInWindows target:rect  item:item];
                
            }break;
            case AWSGuidelinesItemPotionType_Bottom:
            {
                item.tipsView.frame  = [self bottomFrame:soureceViewInWindows target:rect  item:item];
                
            }break;
            case AWSGuidelinesItemPotionType_Auto:
            {
                 CGRect  tempRect = [self topFrame:soureceViewInWindows target:rect  item:item];
                 CGRect screenBounds = [UIScreen mainScreen].bounds;
                if(CGRectContainsRect(screenBounds, tempRect)){
                    item.tipsView.frame = tempRect;
                }else if (CGRectContainsRect(screenBounds, [self leftFrame:soureceViewInWindows target:rect  item:item])){
                      item.tipsView.frame = [self leftFrame:soureceViewInWindows target:rect  item:item];
                }else if (CGRectContainsRect(screenBounds, [self rightFrame:soureceViewInWindows target:rect  item:item])){
                    item.tipsView.frame = [self rightFrame:soureceViewInWindows target:rect  item:item];
                }else if (CGRectContainsRect(screenBounds, [self bottomFrame:soureceViewInWindows target:rect  item:item])){
                    item.tipsView.frame = [self bottomFrame:soureceViewInWindows target:rect  item:item];
                }
                
            }break;
                
            default:
                break;
        }
        [self refreshMask];
        
        UIBezierPath *transparentPath = [UIBezierPath bezierPathWithRect:CGRectInset(soureceViewInWindows, item.dx, item.dy)];
        if (!CGRectEqualToRect(item.rect,CGRectZero)) {
            transparentPath = [UIBezierPath bezierPathWithRect:CGRectInset(item.rect, item.dx, item.dy)];
        }
       
        
        switch (item.style) {
            case AWSGuidelinesItemStyle_Highlight:{
                //绘制高亮区域
                [self addTransparentPath:transparentPath item:item];
            }break;
            case AWSGuidelinesItemStyle_HighlightDottedline:{
                //绘制高亮区域
                [self addTransparentPath:transparentPath item:item];
                //绘制虚线框
                [self  addTransparentHighlightPath:transparentPath];
            }break;
            default:
                break;
        }
        
        
        [self.contentView addSubview:item.tipsView];
    }else{//没有的话直接认为是外部已经计算好了的
        if(item.tipsView){
          
            [self refreshMask];

            UIBezierPath *transparentPath = [UIBezierPath bezierPathWithRect:CGRectInset(item.rect, item.dx, item.dy)];
            
            switch (item.style) {
                case AWSGuidelinesItemStyle_Highlight:{
                    //绘制高亮区域
                    [self addTransparentPath:transparentPath item:item];
                }break;
                case AWSGuidelinesItemStyle_HighlightDottedline:{
                    //绘制高亮区域
                    [self addTransparentPath:transparentPath item:item];
                    //绘制虚线框
                    [self  addTransparentHighlightPath:transparentPath];
                }break;
                default:
                    break;
            }
            
          [self.contentView addSubview:item.tipsView];
        }
    }
}
-(CGRect)topFrame:(CGRect)soureceViewInWindows target:(CGRect)rect item:(AWSGuidelinesItem*)item{
    CGFloat y = soureceViewInWindows.origin.y - rect.size.height;
    CGFloat x = CGRectGetMaxX(soureceViewInWindows) - rect.size.width;
    x+=item.leftMargin;
    y+=item.topMargin;
    return   CGRectMake(x, y, rect.size.width, rect.size.height);
}

-(CGRect)leftFrame:(CGRect)soureceViewInWindows target:(CGRect)rect item:(AWSGuidelinesItem*)item{
    CGFloat y = 0;
    CGFloat x = 0;
    if(rect.size.height>soureceViewInWindows.size.height){
        CGFloat tempHeight = (rect.size.height - soureceViewInWindows.size.height);
        y = soureceViewInWindows.origin.y - tempHeight;
        x = soureceViewInWindows.origin.x - rect.size.width;
        
    }else{
        CGFloat tempHeight = (soureceViewInWindows.size.height - rect.size.height);
        y = soureceViewInWindows.origin.y + tempHeight;
        x = soureceViewInWindows.origin.x - rect.size.width;
    }
    x+=item.leftMargin;
    y+=item.topMargin;
    return  CGRectMake(x, y, rect.size.width, rect.size.height);
}
-(CGRect)rightFrame:(CGRect)soureceViewInWindows target:(CGRect)rect item:(AWSGuidelinesItem*)item{
    CGFloat y = 0;
    CGFloat x = 0;
    if(rect.size.height>soureceViewInWindows.size.height){
        CGFloat tempHeight = (rect.size.height - soureceViewInWindows.size.height);
        y = soureceViewInWindows.origin.y - tempHeight;
        x = CGRectGetMaxX(soureceViewInWindows);
    }else{
        CGFloat tempHeight = (soureceViewInWindows.size.height - rect.size.height);
        y = soureceViewInWindows.origin.y + tempHeight;
        x = CGRectGetMaxX(soureceViewInWindows);
    }
    x+=item.leftMargin;
    y+=item.topMargin;
    return  CGRectMake(x, y, rect.size.width, rect.size.height);
}
-(CGRect)bottomFrame:(CGRect)soureceViewInWindows target:(CGRect)rect item:(AWSGuidelinesItem*)item{
    CGFloat y = CGRectGetMaxY(soureceViewInWindows);
    CGFloat x = CGRectGetMaxX(soureceViewInWindows) - rect.size.width;
    x+=item.leftMargin;
    y+=item.topMargin;
    return  CGRectMake(x, y, rect.size.width, rect.size.height);
}


-(void)hiddenGuidelines{
    if(self.type == AWSGuidelinesType_Once){
        [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.fillLayer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
        [self.contentView removeFromSuperview];
        [self.fillLayer removeFromSuperlayer];
        self.dataSource = nil;
        self.fillLayer = nil;
        self.stepIndex = 0;
    }else{
        //移除所有当次的视图
        [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        [self.fillLayer.sublayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
        
        self.stepIndex++;
        if(self.stepIndex < self.dataSource.count){
            [self confightOneItem:self.dataSource[self.stepIndex]];
        }else{
            [self.contentView removeFromSuperview];
            [self.fillLayer removeFromSuperlayer];
            self.dataSource = nil;
            self.fillLayer = nil;
            self.stepIndex = 0;
        }
    }
}
-(UIWindow*)curWindow{
    return [UIApplication sharedApplication].keyWindow;
}
-(UIView*)contentView{
    if(!_contentView){
        CGRect screenBounds = [UIScreen mainScreen].bounds;
        _contentView = [[UIView alloc] initWithFrame:screenBounds];
        _contentView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenGuidelines)];
        [_contentView addGestureRecognizer:ges];
    }
    return _contentView;
}
-(void)clearContentView{
    for (UIView * view in _contentView.subviews) {
        [view removeFromSuperview];
    }
    self.stepIndex = 0;
}

- (void)refreshMask {
    UIBezierPath *overlayPath = [self generateOverlayPath];
    self.overlayPath = overlayPath;
}

- (UIBezierPath *)generateOverlayPath {
    UIBezierPath *overlayPath = [UIBezierPath bezierPathWithRect:[UIScreen mainScreen].bounds];
    [overlayPath setUsesEvenOddFillRule:YES];
    return overlayPath;
}
//绘制高亮区域
-(void)addTransparentHighlightPath:(UIBezierPath *)transparentPath{
    [self.overlayPath appendPath:transparentPath];
    self.fillLayer.path = self.overlayPath.CGPath;
}
//绘制虚线区域
- (void)addTransparentPath:(UIBezierPath *)transparentPath  item:(AWSGuidelinesItem*)item{
    CAShapeLayer * shapeLine = [CAShapeLayer layer];
    shapeLine.frame = self.fillLayer.bounds;
    shapeLine.lineJoin = kCALineJoinRound;
    shapeLine.lineDashPattern = @[@(5),@(5)];
    shapeLine.fillColor = [UIColor clearColor].CGColor;
    if (item.lineColor) {
        shapeLine.strokeColor = [UIColor redColor].CGColor;
    }else{
        shapeLine.strokeColor = [UIColor whiteColor].CGColor;
    }

    shapeLine.path = transparentPath.CGPath;
    [self.fillLayer addSublayer:shapeLine];
}

#pragma mark - 懒加载Getter Methods

- (UIBezierPath *)overlayPath {
    if (!_overlayPath) {
        _overlayPath = [self generateOverlayPath];
    }
    
    return _overlayPath;
}

- (CAShapeLayer *)fillLayer {
    if (!_fillLayer) {
        CAShapeLayer *fillLayer = [CAShapeLayer layer];
        fillLayer.frame = self.contentView.bounds;
        [self.contentView.layer addSublayer:fillLayer];
        UIColor *maskColor = [UIColor colorWithWhite:0 alpha:0.35];
        fillLayer.path      = self.overlayPath.CGPath;
        fillLayer.fillRule  = kCAFillRuleEvenOdd;
        fillLayer.fillColor = maskColor.CGColor;
        _fillLayer = fillLayer;
    }
    
    return _fillLayer;
}
@end
